<template>
  <div class="_wz_changePassword">
    <Form ref="passwordForm" :model="changePasswordData" label-position="right" :label-width="120" :rules="validatePassword">
      <FormItem label="旧密码">
        <i-input v-model="changePasswordData.password" type="password" placeholder="请输入旧密码" password />
      </FormItem>
      <FormItem label="新密码" prop="newPassword">
        <i-input v-model="changePasswordData.newPassword" type="password" placeholder="请输入新密码" password />
      </FormItem>
      <FormItem label="确认密码" prop="pwdCheck">
        <i-input v-model="changePasswordData.pwdCheck" type="password" placeholder="请输入确认密码" password />
      </FormItem>
      <FormItem>
        <span style="color: #ed4014;">密码由8-16位数字、字母或符号组成,至少含2种以上字符（-_!@#%^&*()+=）,勿重复字母或数字</span>
      </FormItem>
      <FormItem>
        <Button type="primary" @click="changePasswordOk">确定</Button>
      </FormItem>
    </Form>
  </div>
</template>
<script>


import {getCurrentInstance,inject,nextTick,reactive, toRefs,toRef,onBeforeMount,onMounted,onBeforeUpdate,onUpdated,onBeforeUnmount,onUnmounted, ref,defineComponent,toRaw,watch} from 'vue'
import { useRouter,useRoute } from "vue-router";

import { useMainStore } from '../../store'  //pinia 使用 类似 vuex
import { storeToRefs } from 'pinia'
import {getMenu} from "@/util/getMenu";
//pinia 使用 类似 vuex
const mainStore = useMainStore() //pinia 使用 类似 vuex

//reactive
export default defineComponent({
  name: 'changePassword',//组件名称
  components: {},//组件引用
  props:['loginSource'],//是否从登录来 loginSource  true
  setup (props,context) {


    const apiUrl = inject('$apiUrl'); // 变量全局化 后台地址
    const $axios = inject('$axiosInterceptor');// 变量全局化 axios
    const $ViewUIPlus = inject('$ViewUIPlus');//引用全局组件
    const router = useRouter();//路由跳转使用


    const state = reactive({
      changePasswordData: {
        password:'',
        newPassword:'',
        pwdCheck:'',
      },//修改密码表单数据

      validatePassword: {
        newPassword: [
          { message: "请输入新密码", required: true,  trigger: "blur" },
          {
            validator:(rule, value, callBack) => {
              //密码强度验证
              var reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[-_!@#%^&*()+=])(?!.*(password|123456|qwerty|admin))[a-zA-Z\d-_!@#%^&*()+=]{8,18}$/;   /*定义验证表达式*/

              // sessionStorage.setItem("agentPassword", );
              if (!reg.test(value) ) {
                callBack(new Error('密码由8-16位数字、字母或符号组成,至少含2种以上字符,勿重复字母或数字'));
              } else {
                callBack()
              }
            } , trigger: "blur"},
        ],
        pwdCheck: [
          {required: true, message: '确认密码', trigger: 'blur'},
          {
            validator: (rule, value, callBack) => {
              if (state.changePasswordData.newPassword != value) {
                callBack(new Error('新密码和确认密码应相同'));
              } else {
                callBack()
              }
            }, trigger: 'blur'
          }
        ]
      },

    });




    // 用于获取$refs
    const passwordForm = ref();


    //修改密码提交
    const changePasswordOk = ()=> {
      passwordForm.value.validate(async(valid) => {
        if(valid){
          $ViewUIPlus.Spin.show()
          $axios.post(apiUrl.systemLoginUpdatePass,state.changePasswordData).then(async(res) => {
            $ViewUIPlus.Spin.hide()

            if (!!res) {
              state.changePasswordData = {};
              if(!props.loginSource) {//关闭弹层
                context.emit('closeFun', true)
              }


              //密码强度验证
              $ViewUIPlus.Message.success({
                content: "修改成功",
                onClose:  async()=> {

                  let loginData = JSON.parse(sessionStorage.getItem("loginData"));
                  loginData.userInfo.strength = 1;
                  sessionStorage.setItem("loginData", JSON.stringify(loginData));


                  mainStore.userData = loginData;//用户数据


                  if(!!props.loginSource){//跳转首页
                    let menuUrl = await getMenu()
                    router.push({ path: menuUrl, query: {}})
                  }else{//关闭弹层

                  }

                }
              });

            }


          }).catch((err) => {
            console.log("失败", err)
          })
        }else{
          $ViewUIPlus.Message.error('请正确填写表单');
        }
      })
    }



    // 其他的生命周期
    onBeforeMount (() => {//beforeMount挂载前状态 // console.log("App ===> 相当于 vue2.x 中 beforeMount")

    })
    onMounted (() => {//mounted 挂载结束状态  // console.log("App ===> 相当于 vue2.x 中 mounted")

    })

    // 注意，onBeforeUpdate 和 onUpdated 里面不要修改值
    onBeforeUpdate (() => {//beforeUpdate 更新前状态 // console.log("App ===> 相当于 vue2.x 中 beforeUpdate")

    })

    onUpdated (() => {//updated 更新完成状态 // console.log("App ===> 相当于 vue2.x 中 updated")

    })

    onBeforeUnmount (() => {//beforeDestroy 销毁前状态  // console.log("App ===> 相当于 vue2.x 中 beforeDestroy")
    })

    onUnmounted (() => {//destroyed 销毁完成状态  // console.log("App ===> 相当于 vue2.x 中 destroyed")
    })

    return {
      ...toRefs(state),
      changePasswordOk,//修改密码提交
      passwordForm,//ref 使用

    }
  }
})


</script>
<style lang="less">
._wz_changePassword {
  padding: 30px 0 0 0;
  width: 100%;
  height: 100%;
  background: #fff;
}
</style>
